package com.friend.uu;

import android.app.Activity;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;

public class BluetoothRecorderActivity extends Activity implements View.OnClickListener {

    private AudioRecordUtils aRecord = null;
    private File audioFile = null;
    private MediaPlayer mediaPlayer = null;
    private Button bt_play, bt_record, bt_openBluetoothMIC;
    private TextView tv_recordTime, tv_playTime, tv_duration;
    private SeekBar seekBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_bluetooth_recorder);

        bindView();
        aRecord = new AudioRecordUtils(44100, AudioFormat.CHANNEL_IN_MONO, 16);
        new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        updateTime();
                    }
                });
            }
        }, new Date(), 1000);
    }

    private void bindView() {
        bt_record = findViewById(R.id.bt_record);
        bt_record.setOnClickListener(this);
        bt_play = findViewById(R.id.bt_play);
        bt_play.setOnClickListener(this);
        bt_openBluetoothMIC = findViewById(R.id.bt_openBluetoothMIC);
        bt_openBluetoothMIC.setOnClickListener(this);
        findViewById(R.id.btn_bluetooth_recorder_back).setOnClickListener(this);
        tv_recordTime = findViewById(R.id.tv_recordTime);
        tv_playTime = findViewById(R.id.tv_playTime);
        tv_duration = findViewById(R.id.tv_duration);
        seekBar = findViewById(R.id.seekBar);
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                if (mediaPlayer != null && mediaPlayer.isPlaying()) {
                    mediaPlayer.seekTo(seekBar.getProgress());
                }
            }
        });
    }

    //计时器
    int seconds = 0;
    boolean isRecording = false;

    private void updateTime() {
        //播放显示时间
        if (mediaPlayer != null && mediaPlayer.isPlaying()) {
            int du, cu;
            du = mediaPlayer.getDuration();
            cu = mediaPlayer.getCurrentPosition();
            seekBar.setEnabled(true);
            seekBar.setMax(du);
            seekBar.setProgress(cu);
            tv_playTime.setText(String.format(Locale.getDefault(),
                    "%02d:%02d:%02d", cu / 3600000,
                    cu % 3600000 / 60000, cu % 60000 / 1000));
            tv_duration.setText(String.format(Locale.getDefault(),
                    "%02d:%02d:%02d", du / 3600000,
                    du % 3600000 / 60000, du % 60000 / 1000));
        } else {
            seekBar.setEnabled(false);
            bt_play.setText(R.string.startPlay);
            bt_record.setEnabled(true);
            tv_duration.setText(R.string.timeFormat);
            tv_playTime.setText(R.string.timeFormat);
        }
        //录音计时
        if (isRecording) {
            tv_recordTime.setText(String.format(Locale.getDefault(),
                    "%02d:%02d:%02d", seconds / 3600,
                    seconds % 3600 / 60, seconds % 60));
            seconds++;
        } else {
            tv_recordTime.setText(R.string.timeFormat);
            seconds = 0;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bt_record:
                if (bt_record.getText() == getString(R.string.startRecord)) {
                    startRecord();
                } else {
                    stopRecord();
                }
                break;
            case R.id.bt_play:
                if (bt_play.getText() == getString(R.string.startPlay)) {
                    startPlay();
                } else {
                    stopPlay();
                }
                break;
            case R.id.bt_openBluetoothMIC:
                final AudioManager audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
                boolean isOn = audioManager.isBluetoothScoOn();
                audioManager.setBluetoothScoOn(!isOn);
                //开关蓝牙MIC
                if (isOn) {
                    audioManager.stopBluetoothSco();
                } else {
                    audioManager.startBluetoothSco();
                }
                //检查蓝牙MIC开关状态
                if (isOn) {
                    bt_openBluetoothMIC.setText(R.string.closeBluetoothMIC);
                } else {
                    bt_openBluetoothMIC.setText(R.string.openBluetoothMIC);
                }
                break;
            case R.id.btn_bluetooth_recorder_back:
                finish();
                break;
        }
    }

    /**
     * 开始录音
     */
    private void startRecord() {
        File dir = new File(Environment.getExternalStorageDirectory(),
                "BluetoothRecording");
        if (!dir.exists() || !dir.isDirectory()) {
            if (!dir.mkdir()) {
                Toast.makeText(this, "创建目录失败：" + dir, Toast.LENGTH_SHORT).show();
                return;
            }
        }
        Calendar mCalendar = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS", Locale.getDefault());
        String fileName = sdf.format(mCalendar.getTime()) + ".wav";
        audioFile = new File(dir, fileName);
        new Thread(new Runnable() {
            @Override
            public void run() {
                aRecord.startRecord(BluetoothRecorderActivity.this, audioFile);
            }
        }).start();
        bt_play.setEnabled(false);
        isRecording = true;
        bt_record.setText(R.string.stopRecord);
    }

    /**
     * 停止录音
     */
    private void stopRecord() {
        if (aRecord != null) aRecord.stopRecord();
        bt_play.setEnabled(true);
        isRecording = false;
        bt_record.setText(R.string.startRecord);
    }

    /**
     * 开始播放
     */
    private void startPlay() {
        if (audioFile == null || !audioFile.exists()) {
            Toast.makeText(this, "文件不存在", Toast.LENGTH_LONG).show();
            return;
        }
        String path = audioFile.getAbsolutePath();
        if (mediaPlayer == null) {
            mediaPlayer = new MediaPlayer();
        }
        try {
            mediaPlayer.reset();//必须重置，否则第二次播放会闪退。
            mediaPlayer.setDataSource(path);
            mediaPlayer.prepare();
        } catch (IOException e) {
            Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
        }
        mediaPlayer.start();
        bt_record.setEnabled(false);
        bt_play.setText(R.string.stopPlay);
    }

    /**
     * 停止播放
     */
    private void stopPlay() {
        if (mediaPlayer == null) {
            return;
        }
        mediaPlayer.reset();
        mediaPlayer.release();
        bt_record.setEnabled(true);
        bt_play.setText(R.string.startPlay);
    }
}
